package typejump.sound;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.File;
import java.io.InputStreamReader;

import typejump.InstallManager;

public class NativePlayer implements Player {
	
	private Process process;
	private PrintWriter out;
	private BufferedReader in;
	private Thread eatThread;
	
	private String audioPath = "/home/g/.SwaggerTyper/sound/";

	public NativePlayer() {
		if (createProcess()) {
			//System.out.println("Sounds loaded successfully");
		} else {
			System.err.println("Sounds failed to load!");
		}
	}
	
	private boolean createProcess() {
		File playerFile = InstallManager.getFile("SimpleAudio");
		Process process = null;
		try {
			process = Runtime.getRuntime().exec("SimpleAudio"); //playerFile.getAbsolutePath());
			this.process = process;
			this.out = new PrintWriter(process.getOutputStream(), true);
			this.in = new BufferedReader(new InputStreamReader(process.getInputStream()));
			
			if (eatThread == null) {
				eatThread = new Thread() {
					@Override
					public void run() {
						while (true) {
							try {
//								System.out.println("sound> " + in.readLine());
							} catch (Exception e) {
								try { Thread.sleep(50); }
								catch (Exception ex) {} ;
							}
						}
					}
				};
				eatThread.start();
			}
			
			return true;
		} catch (Exception e) {
			System.err.println("Sound error: " + e + ": " + e.getMessage());
			return false;
		}
	}
	
	private void cmd(String cmd, String filename) {
		if (out == null) return;
		filename = audioPath + filename;
		out.println(cmd + " "  + filename);
	}

	@Override
	public void loop(String filename) {
		cmd("loop", filename);
	}

	@Override
	public void pause(String filename) {
		cmd("pause", filename);
	}

	@Override
	public void pauseAll(String filename) {
		cmd("pauseall", filename);
	}

	@Override
	public void play(String filename) {
		cmd("play", filename);
	}

	@Override
	public void stop(String filename) {
		cmd("stop", filename);
	}

	@Override
	public void stopAll(String filename) {
		cmd("stopall", filename);
	}

	@Override
	public void unpause(String filename) {
		cmd("unpause", filename);
	}

	@Override
	public void unpauseAll(String filename) {
		cmd("unpauseall", filename);
	}
}
